package com.nf.mvc.adapter;

import com.nf.mvc.HandlerAdapter;
import com.nf.mvc.ViewResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 这个Adapter可以作为入门级Adapter来讲解，没有用在框架中，
 * Handler是一个Method，与PropertiesHandlerMappings配合使用
 */
public class RequestResponseAdapter implements HandlerAdapter {
    @Override
    public boolean supports(Object handler) {
        if (handler instanceof Method) {
            Method m = (Method) handler;
            Class<?> firstParamClass = m.getParameters()[0].getType();
            Class<?> secondParamClass = m.getParameters()[1].getType();
            // 方法有2个参数，并且第一个是HttpServletRequest类型，第二个是HttpServletResponse类型
            return m.getParameterCount() == 2
                    && HttpServletRequest.class.isAssignableFrom(firstParamClass)
                    && HttpServletResponse.class.isAssignableFrom(secondParamClass);
        }
        return false;
    }

    @Override
    public ViewResult handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Method m = (Method) handler;
        Object o = m.getDeclaringClass().newInstance();
        return (ViewResult) m.invoke(o, request, response);
    }
}
